<template>
  <div class="login-container">
    <div class="login-background">
      <div class="login-card">
        <div class="login-header">
          <div class="logo">
            <i class="pi pi-building"></i>
            <h1>宿舍管理系统</h1>
          </div>
          <p class="subtitle">欢迎回来，请登录您的账户</p>
        </div>

        <el-form 
          @submit.prevent="handleLogin" 
          :model="loginForm" 
          :rules="rules" 
          ref="loginFormRef"
          class="login-form"
          label-position="top"
        >
          <el-form-item label="用户名" prop="username">
            <template #label>
              <div class="form-label">
                <el-icon><User /></el-icon>
                用户名
              </div>
            </template>
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              clearable
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <template #label>
              <div class="form-label">
                <el-icon><Lock /></el-icon>
                密码
              </div>
            </template>
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              show-password
              clearable
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captchaCode">
            <template #label>
              <div class="form-label">
                <el-icon><Picture /></el-icon>
                验证码
              </div>
            </template>
            <div class="captcha-container">
              <el-input
                v-model="loginForm.captchaCode"
                placeholder="请输入验证码"
                size="large"
                clearable
                class="captcha-input"
                @keyup.enter="handleLogin"
                @input="clearCaptchaError"
              >
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
              <div class="captcha-image-container" @click="refreshCaptcha">
                <img 
                  v-if="captchaImage && !isCaptchaLoading" 
                  :src="captchaImage" 
                  alt="验证码" 
                  class="captcha-image"
                  @error="handleImageError"
                />
                <div v-else class="captcha-placeholder">
                  <el-icon><Refresh /></el-icon>
                  <span>{{ isCaptchaLoading ? '加载中...' : '点击刷新' }}</span>
                </div>
              </div>
            </div>
            <!-- 这里显示验证码的错误信息 -->
            <div v-if="captchaError" class="captcha-error">
              {{ captchaError }}
            </div>
          </el-form-item>

          <el-form-item prop="agreeToTerms">
            <div class="form-options">
              <el-checkbox v-model="loginForm.agreeToTerms" size="large">
                我已阅读并同意《用户协议》和《隐私政策》
              </el-checkbox>
            </div>
          </el-form-item>

          <el-alert
            v-if="loginError"
            :title="loginError"
            type="error"
            show-icon
            :closable="false"
            class="error-alert"
          />

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="isLoading"
              @click="handleLogin"
              class="login-button"
              style="width: 100%"
            >
              {{ isLoading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Picture, Key, Refresh } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { getCaptcha } from '@/apis/loginAPI'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const isLoading = ref(false)
const isCaptchaLoading = ref(false)
const loginError = ref('')
const loginFormRef = ref()
const captchaImage = ref('')
const captchaKey = ref('')
const captchaError = ref('') // 专门用于验证码错误提示

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  captchaCode: '',
  agreeToTerms: false
})

// Element Plus 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captchaCode: [
    { 
      required: true, 
      message: '请输入验证码', 
      trigger: ['blur', 'change'] 
    },
    { 
      min: 4, 
      max: 6, 
      message: '验证码长度在 4 到 6 个字符', 
      trigger: ['blur', 'change'] 
    }
  ],
  agreeToTerms: [
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请先同意用户协议和隐私政策'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}

// 清除验证码错误
const clearCaptchaError = () => {
  if (loginForm.captchaCode.trim() !== '') {
    captchaError.value = ''
  }
}

// 处理图片加载错误
const handleImageError = () => {
  console.error('验证码图片加载失败')
  ElMessage.error('验证码加载失败，请点击刷新')
  captchaImage.value = ''
}

// 获取验证码
const fetchCaptcha = async () => {
  isCaptchaLoading.value = true
  captchaImage.value = '' // 清空之前的图片
  
  try {
    const result = await getCaptcha()
    console.log('验证码接口返回:', result)
    
    if (result.code === 200 || result.code === 0) { // 根据你的API调整成功码
      const data = result.data || result
      
      if (data.captchaImage && data.captchaKey) {
        captchaImage.value = data.captchaImage
        captchaKey.value = data.captchaKey
        console.log('验证码设置成功')
      } else {
        throw new Error('验证码数据不完整')
      }
    } else {
      throw new Error(result.msg || '获取验证码失败')
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
    ElMessage.error('获取验证码失败: ' + (error.message || '请检查网络连接'))
    captchaImage.value = ''
  } finally {
    isCaptchaLoading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  loginForm.captchaCode = '' // 清空验证码输入
  captchaError.value = '' // 清空验证码错误
  fetchCaptcha()
}

// 处理登录
const handleLogin = async () => {
  // 清除之前的错误
  loginError.value = ''
  captchaError.value = ''

  // 验证验证码是否存在
  if (!captchaKey.value) {
    ElMessage.error('请先获取验证码')
    return
  }

  // 手动验证验证码是否为空
  if (!loginForm.captchaCode || loginForm.captchaCode.trim() === '') {
    captchaError.value = '请输入验证码'
    return
  }

  // 使用Element Plus表单验证
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
  } catch (error) {
    // 如果验证失败，检查是否是验证码的错误
    const errors = error.fields || {}
    if (errors.captchaCode && errors.captchaCode.length > 0) {
      captchaError.value = errors.captchaCode[0].message
    }
    return // 验证失败，不继续执行
  }

  isLoading.value = true

  try {
    // 调用登录方法，添加验证码参数
    await authStore.login({
      account: loginForm.username.trim(),
      password: loginForm.password.trim(),
      captchaCode: loginForm.captchaCode.trim(),
      captchaKey: captchaKey.value
    })

    // 登录成功
    ElMessage.success('登录成功，欢迎回来！')
    
    // 跳转到首页
    router.push('/')
  } catch (error) {
    // 登录失败
    loginError.value = error.message || '登录失败，请检查用户名和密码'
    ElMessage.error(loginError.value)
    
    // 登录失败时刷新验证码
    refreshCaptcha()
  } finally {
    isLoading.value = false
  }
}

// 组件挂载时获取验证码
onMounted(() => {
  fetchCaptcha()
})
</script>

<style scoped>
.login-container {
  min-height: 100vh !important;
  height: 100vh !important;
  display: flex !important;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100% !important;
  overflow: hidden;
  margin: 0 !important;
  padding: 0 !important;
  z-index: 9999;
}

.login-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.1;
}

.login-background {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 400px;
  padding: 20px;
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: slideUp 0.6s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 10px;
}

.logo i {
  font-size: 2.5rem;
  color: #667eea;
}

.logo h1 {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 700;
  color: #2d3748;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.subtitle {
  color: #718096;
  font-size: 0.95rem;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

/* Element Plus 表单样式 */
.login-form .el-form-item {
  margin-bottom: 20px;
}

.login-form .el-form-item__label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #4a5568;
  font-size: 0.9rem;
}

.login-form .el-form-item__label .el-icon {
  color: #667eea;
  font-size: 0.9rem;
}

.login-form .el-input__wrapper {
  border-radius: 12px;
  border: 2px solid #e2e8f0;
  background: #f8fafc;
  transition: all 0.3s ease;
  box-shadow: none;
}

.login-form .el-input__wrapper:hover {
  border-color: #cbd5e0;
}

.login-form .el-input__wrapper.is-focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  background: white;
}

.login-form .el-input__inner {
  color: #2d3748;
  font-size: 0.95rem;
}

.login-form .el-input__prefix {
  color: #667eea;
}

.login-form .el-checkbox__label {
  color: #4a5568;
  font-size: 0.9rem;
}

.login-form .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #667eea;
  border-color: #667eea;
}

.login-form .el-button--primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  border-radius: 12px;
  height: 48px;
  font-size: 1rem;
  font-weight: 600;
  transition: all 0.3s ease;
}

.login-form .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
}

.login-form .el-button--primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 验证码样式 */
.captcha-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image-container {
  position: relative;
  width: 120px;
  height: 40px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  background: #f8fafc;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
}

.captcha-image-container:hover {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.captcha-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  color: #a0aec0;
  font-size: 0.8rem;
}

/* 验证码错误提示 */
.captcha-error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.error-alert {
  background: #fed7d7;
  border: 1px solid #feb2b2;
  color: #c53030;
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
}

.error-alert i {
  font-size: 1rem;
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .login-card {
    background: rgba(26, 32, 44, 0.95);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .logo h1 {
    color: #f7fafc;
  }
  
  .subtitle {
    color: #a0aec0;
  }
  
  .form-label {
    color: #e2e8f0;
  }
  
  .form-input :deep(.p-inputtext),
  .form-input :deep(.p-password input) {
    background: #2d3748;
    border-color: #4a5568;
    color: #f7fafc;
  }
  
  .form-input :deep(.p-inputtext:focus),
  .form-input :deep(.p-password input:focus) {
    background: #1a202c;
  }
  
  .checkbox-label {
    color: #e2e8f0;
  }
  
  .captcha-image-container {
    background: #2d3748;
    border-color: #4a5568;
  }
  
  .captcha-placeholder {
    color: #718096;
  }
  
  .captcha-error {
    color: #f56c6c;
  }
}
</style>